<?php
class AMSModuleConfiguration {
    var $modules;
    /**
     * Returns module path by its name
     * @param string $moduleName
     */
    protected function findModule($moduleName,&$namespace) {
        $modulePath = str_replace('_',DS,$moduleName);
        foreach (explode(',',MODULE_NAMESPACES) as $namespace) {
            $search = sprintf(MODULE_PATH,$namespace,$modulePath) . DS . MODULE_CONFIG_FILE;
            if (file_exists($search)) return $search;
        }
        return false;
    }
    /**
     * Initialize module configuration files
     */
    protected function initModulesConfiguration() {
        $enabledModules=array();
        foreach (glob(MODULE_CONFIGS) as $configFile) {
            $xml = simplexml_load_file($configFile);
            foreach ($xml->children() as $child) {
                if (isset($child->enabled) && ((int)$child->enabled==1))
                    $enabledModules[]=$child->getName();
            }
        }
        foreach ($enabledModules as $moduleName) {
           if ($configFile = $this->findModule($moduleName,$namespace)) {
               $this->initModule($configFile, $moduleName,$namespace);
           }
        }
    }
    /**
     * Read config file and initialize module
     * @param string $configPath
     */
    protected function initModule($configPath, $moduleName,$namespace) {
        $modules = $this->modules;
        $xml = simplexml_load_file($configPath);
        if (isset($xml->$moduleName)) {
            $moduleData['module'] = $moduleName;
            $moduleData['version'] = (string)$xml->$moduleName->version;
            $moduleData['namespace'] = $namespace;
            if (isset($xml->models)) foreach ($xml->models->children() as $aliasNode) {
                    $alias = (string)$aliasNode->getName();
                    $modules['models'][$alias] = $moduleData;
            }
            if (isset($xml->routers)) foreach ($xml->routers->children() as $routerNode) {
                $alias = (string)$routerNode;
                $modules['routers'][$alias] = $moduleData;
                $modules['routers'][$alias]['type'] = (string)$routerNode->getName();
            }
        }
        $modules['namespace'][$moduleName] = $namespace;
        $this->modules = $modules;
    }
    public function init() {
        $this->initModulesConfiguration();
        return $this->modules;
    }
}

class Registry extends AMS_Object {
    protected $modules;
    public function __construct($modulesConfiguration) {
        $this->modules = $modulesConfiguration;
        $GLOBALS['registry'] = $this;
    }
    public function getModules() {
        return $this->modules;
    }
    public function findModuleNamespace($class) {
        $module = substr($class,0, strpos($class , '_',1+strpos($class , '_')));
        if (isset($this->modules['namespace'][$module]))
            return $this->modules['namespace'][$module];
        else
            return 'core';
    }
}
?>
